const express = require("express")
const router = express.Router()
const Leave = require("../models/leave")

router.post("/", async (req, res) => {
    try {
        const result = await Leave.addLeave(req.body)
        console.log(result);
        if (result > 0) {
            res.status(200).json({ code: 200, message: "请假记录添加成功" })
        } else {
            res.status(200).json({ code: 200, message: "请假记录添加失败" })
        }

    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

router.get("/", async (req, res) => {
    try {
        const { currentPage, pageSize, searchMsg } = req.query;
        const leave = await Leave.getAllLeave(currentPage, pageSize, searchMsg)
        return res.status(200).json({ code: 200, data: leave.data, total: leave.total })
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
}
)
router.delete("/:id", async (req, res) => {
    try {
        const { id } = req.params
        const result = await Leave.deleteLeave(id)
        if (result > 0) {
            res.status(200).json({ code: 200, message: "请假记录删除成功" })
        } else[
            res.status(200).json({ code: 200, message: "未找到" })
        ]

    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

router.put("/:id", async (req, res) => {
    try {
        const { leave_approved_by, type } = req.body
        const { id } = req.params
        const update = await Leave.updateLeave(leave_approved_by, type, id)
        if (update > 0) {
            res.status(200).json({ code: 200, message: "更新成功" })
        } else[
            res.status(200).json({ code: 200, message: "未找到" })
        ]

    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

module.exports = router